package com.dayu.finecomm.protocol.codec;

import java.util.Arrays;

import com.dayu.finecomm.utils.Helpers;

import io.netty.buffer.ByteBuf;

/***
 * 
 * 短包格式的解码器，适用于短报文（不分包），例如RPS8000：
 * 
 * 0x88 0x88 ... 0x88 0xDD
 * 
 * @author Lijiajie
 * 
 * @param <T>
 */
public abstract class UDPPacketFrameDecoder<T> extends ProtocolDecoder<T> {

	public final byte[] startMagic;
	public final byte[] endMagic;
	public final int minLength;

	public UDPPacketFrameDecoder(byte[] startMagic, byte[] endMagic, int minLength) {

		this.startMagic = startMagic;
		this.endMagic = endMagic;

		this.minLength = minLength;
	}

	public UDPPacketFrameDecoder(String startMagic, String endMagic, int minLength) {

		this(startMagic.getBytes(Helpers.ASCII), endMagic.getBytes(Helpers.ASCII), minLength);
	}

	public int checkStart(ByteBuf in) {
		return 0;
	}

	@Override
	public int check(ByteBuf in) {

		if (in.readableBytes() < minLength && in.readableBytes() < startMagic.length)
			return -1;

		ByteBuf b1 = in.readBytes(startMagic.length);

		if (!Arrays.equals(b1.array(), startMagic)) {
			return -1;
		}

		if (minLength - startMagic.length > 0) {
			if (in.readableBytes() >= minLength - startMagic.length) {
				in.skipBytes(minLength - startMagic.length);
			} else {
				return -1;
			}
		}

		int mark = -1;

		if (in.readableBytes() >= endMagic.length) {

			in.skipBytes(in.readableBytes() - endMagic.length);

			b1 = in.readBytes(endMagic.length);

			if (Arrays.equals(b1.array(), endMagic)) {

				return in.readerIndex() + in.readableBytes();
			}

		}

		return mark;
	}
}
